package org.sanm.webSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.sanm.utils.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.net.URI;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketHandler extends TextWebSocketHandler {
    @Autowired
    ObjectMapper objectMapper;
    // 存储连接的会话
//    private final Set<WebSocketSession> sessions = ConcurrentHashMap.newKeySet();

    public static final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Map<String, String> params = getQuery(session.getUri());
        // 新连接建立时加入会话集合
        sessionMap.put(params.get("id"), session);
        sendMessage(session, new Message(MessageType.NOTICE, "服务器", "服务器", params.get("id"), "连接成功！"));

        System.out.println("新连接建立时加入会话集合：" + sessionMap.size());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        // 解析消息内容
        Message chatMessage = new ObjectMapper().readValue(payload, Message.class);
        if (chatMessage.getMessageType() == MessageType.HEART) {
            handleHeart(session);
        }
        if(chatMessage.getMessageType() == MessageType.PERSON){
            handlePerson(chatMessage);
        }
        if(chatMessage.getMessageType() == MessageType.ROOM){
            handleRoom(chatMessage);
        }
        if(chatMessage.getMessageType() == MessageType.CREATE_ROOM){
            handleCreateRoom(chatMessage);
        }
        if(chatMessage.getMessageType() == MessageType.JOIN_ROOM){
            handleJoinRoom(chatMessage);
        }
        if(chatMessage.getMessageType() == MessageType.EXIT_ROOM){
            handleExitRoom(chatMessage);
        }
        if(chatMessage.getMessageType() == MessageType.MEMBER_LIST){
            handleMemberList(chatMessage);
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接关闭时移除会话
        Map<String, String> params = getQuery(session.getUri());
        String id = params.get("id");
        sessionMap.remove(id);
        Room room = Room.exitRoom(id);


        System.out.println("连接关闭时移除会话：" + sessionMap.size());
    }

    private void handleHeart(WebSocketSession session) throws Exception {

        sendMessage(session, new Message(MessageType.HEART, "服务器", "服务器", "你", "pong"));
    }

    public void handlePerson(Message message) throws Exception {
        String targetId = message.getTargetId();
        WebSocketSession session = sessionMap.get(targetId);
        sendMessage(session, message);

    }

    public void handleRoom(Message message) throws Exception {
        Room.handleRoomMessage(message);
    }

    public  void handleCreateRoom(Message message) throws Exception {
        Room.createRoom(message);

    }

    public void handleJoinRoom(Message message) throws Exception {
        Room.joinRoom(message);
    }

    public void handleExitRoom(Message message) throws Exception {
        String targetId = message.getTargetId();
        String senderId = message.getSenderId();
        synchronized (targetId) {
            Room room = Room.get(targetId);
            if(room == null){
                return;
            }
            Room.exitRoom(senderId);

        }

    }

    public void handleMemberList(Message message) throws Exception {
        String senderId = message.getSenderId();
        WebSocketSession session = sessionMap.get(senderId);
        String targetId = message.getTargetId();
        Room room = Room.get(targetId);
        Message m = new Message(MessageType.MEMBER_LIST, "服务器", "服务器", senderId, room.getMemberList());
        sendMessage(session, m);
    }


    public void sendMessage(WebSocketSession session, Message message) throws Exception {
        if(session == null || !session.isOpen()){
            return;
        }
        session.sendMessage(new TextMessage(
                objectMapper.writeValueAsString(message)
        ));
    }

    public static void sendMessage(String userId, Message message) throws Exception {
        WebSocketSession session = sessionMap.get(userId);
        WebSocketHandler webSocketHandler = SpringUtil.getBean(WebSocketHandler.class);
        webSocketHandler.sendMessage(session, message);
    }

    private Map getQuery(URI uri) {
        Map<String, String> map = new HashMap<>();
        if (uri == null) {
            return map;
        }
        String query = uri.getQuery();
        String[] arr = query.split("&");
        for (String s : arr) {
            String[] split = s.split("=");
            map.put(split[0], split[1]);
        }

        return map;
    }
}

